<?php

class LoginSinaClass {

	function __construct() {
		add_action('init', array($this, 'connect_init'), 1);
	}

	//新浪微博登录
	function connect_init() {
		if ($_GET['connect'] == 'sina') {
			$this -> login('sina');
		} elseif ($_GET['connect'] == 'sinabind') {
			if (!is_user_logged_in()) {
				wp_safe_redirect(home_url());
				exit ;
			}
			$this -> login('sinabind');
		} elseif ($_GET['callback'] == 'sinacallback') {
			$logintype = $_GET['logintype'];
			$this -> callback($logintype);
			if ($logintype == 'sinabind') {
				$this -> bind();
			} else {
				$this -> dispose();
			}
		} elseif ($_GET['connect'] == 'sinaunwrap') {
			$this -> unwrap();
		}
	}

	//登录成功回调函数 获取Access Token和UID
	function login($type) {
		$_SESSION['rurl'] = $_REQUEST["r"];
		$_SESSION['state'] = md5(uniqid(rand(), true));
		$login_url = "https://api.weibo.com/oauth2/authorize?client_id=" . new_option('sina_app_key') . "&response_type=code&redirect_uri=" . urlencode(home_url('/') . "?callback=sinacallback&logintype=" . $type) . "&state=" . $_SESSION['state'];
		header("Location:$login_url");
		exit ;
	}

	//获取用户信息
	function callback($type) {
		if ($_REQUEST['state'] == $_SESSION['state']) {
			$url = "https://api.weibo.com/oauth2/access_token";
			$data = "client_id=" . new_option('sina_app_key') . "&client_secret=" . new_option('sina_app_secret') . "&grant_type=authorization_code&redirect_uri=" . urlencode(home_url('/') . "?callback=sinacallback&logintype=" . $type) . "&code=" . $_REQUEST["code"];
			$output = json_decode(do_post($url, $data));
			$_SESSION['access_token'] = $output -> access_token;
			$_SESSION['uid'] = $output -> uid;
		} else {
			exit('错误信息：CSRF不匹配。');
		}
	}

	//登录成功后数据处理

	function bind() {
		if (!is_user_logged_in())
			exit('错误信息：请继续登录');
		global $wpdb;
		$session_uid = $_SESSION['uid'];
		$openid_db = $wpdb -> get_var("SELECT uid FROM `{$wpdb->users}` where uid='{$session_uid}'");

		if (empty($session_uid)) {
			exit('错误信息：uid是空的');
		} elseif ($openid_db) {
			exit('错误信息：The account has been!<a href="' . $_SESSION['rurl'] . '">点击返回</a>');
		} else {
			$userid = get_current_user_id();
			$return = $wpdb -> query("UPDATE `{$wpdb->users}` SET uid = '{$session_uid}' WHERE ID = '{$userid}'");
			$str = json_decode($this -> get_user_info());
			$sinaimg = $str -> avatar_large;
			$data = update_user_meta($userid, 'sinauserimg', $sinaimg);
			wp_redirect($_SESSION['rurl']);
			exit();
		}
	}

	//新浪微博绑定

	function get_user_info() {
		$get_user_info = "https://api.weibo.com/2/users/show.json?uid=" . $_SESSION['uid'] . "&access_token=" . $_SESSION['access_token'];
		return get_url_contents($get_user_info);
	}

	//新浪解绑

	function dispose() {
		global $wpdb;
		if (empty($_SESSION['uid'])) {
			header("Location:", home_url('/'));
			exit ;
		}
		$query = "SELECT ID FROM `{$wpdb->users}` where uid='{$_SESSION["uid"]}'";
		$uid_db = $wpdb -> get_var($query);
		if (is_numeric($uid_db)) {
			$user_ID = $uid_db;
			$user = get_user_by('id', $user_ID);
			wp_set_current_user($user_ID, $user -> user_login);
			wp_set_auth_cookie($user_ID);
			do_action('wp_login', $user -> user_login);
			wp_redirect($_SESSION['rurl']);
			exit();
		} else {
			$login_name = wp_create_nonce($_SESSION['uid']);
			$pass = wp_create_nonce(microtime());
			$str = json_decode($this -> get_user_info());
			$username = $str -> screen_name;
			$userimg = $str -> avatar_large;
			$http = is_ssl() ? "https://" : "http://";
			$userdata = array('user_login' => $login_name, 'display_name' => $username, 'user_pass' => $pass, 'nickname' => $username, 'first_name' => $username, 'sinauserimg' => $userimg, 'user_email' => $login_name . "@sina.com");
			$user_id = wp_insert_user($userdata);
			if (is_wp_error($user_id)) {
				exit('错误信息：' . $user_id -> get_error_message() . '<a href="' . $_SESSION['rurl'] . '">点击返回</a>');
			} else {
				$ff = $wpdb -> query("UPDATE `{$wpdb->users}` SET uid = '{$_SESSION["uid"]}' WHERE ID = '{$user_id}'");
				if ($ff) {
					wp_set_current_user($user_id);
					wp_set_auth_cookie($user_id, true, false);
					wp_redirect($_SESSION['rurl']);
				}
			}
			exit();
		}
	}

	function unwrap() {
		if (!is_user_logged_in())
			exit('错误信息：请继续登录');
		global $wpdb;
		$userid = get_current_user_id();
		$wpdb -> query("UPDATE `{$wpdb->users}` SET uid = '' WHERE ID = '{$userid}'");
		delete_user_meta($userid, 'sinauserimg');
	}

}
?>